<template>
    <div class="signin_body">
      <div class="signin_container">
        <div class="head">
          <img class="logo" src="../../assets/logo.png" />
          <div class="name">
            <div class="title">高中信息技术</div>
            <div class="tips">题库系统</div>
          </div>
        </div> 
        <el-form label-position="top" :rules="state.rules" :model="state.ruleForm" ref="signinForm" class="signinForm">        
         <el-form-item label="手机（11位数字）" prop="phone">
          <div class="send_phone_code"> 
            <el-input type="text" v-model="state.ruleForm.phone" autocomplete="off" clearable @blur="checkPhoneUsableBlur"></el-input>
             <div v-show="state.phoneNumberOk"><el-icon size="large"><SuccessFilled /></el-icon></div>
             <div v-show="state.phoneNumberOk == false"><el-icon size="large"><CircleCloseFilled /></el-icon></div>
          </div>
          </el-form-item>
          <el-form-item label="图形验证码（不区分大小写）" prop="captchaCode">
            <div class="send_phone_code">  
                <el-input type="text" v-model="state.ruleForm.captchaCode" autocomplete="off" clearable @blur="checkCapchaCodeBlur"></el-input>
                <div v-show="state.captchaCodeOk"><el-icon size="large"><SuccessFilled /></el-icon></div>
                <div v-show="state.captchaCodeOk == false"><el-icon size="large"><CircleCloseFilled /></el-icon></div>
                <img :src="state.captcha_picture" class="captcha_picture" @click="updatacaptcha" />
            </div>
          </el-form-item>
          <el-form-item label="短信" prop="phone_code" >
            <div class="send_phone_code" ref="sendPhoneCoseRef">  
                <el-input type="text" v-model="state.ruleForm.phoneCode" autocomplete="off" :disabled="state.phoneCodeInput" clearable @blur="checkPhoneCodeBlur"></el-input>
                <el-text v-show="state.phoneCodeOK">  <el-icon size="large"><SuccessFilled /></el-icon></el-text>
                <el-button type="primary" round size="small" @click="getPhoneCodeClick()" :disabled="state.getPhoneCodeButtonOK">获取短信</el-button>
            </div> 
        </el-form-item>
     
          <div class="twoButton"> 
            <el-button type="primary" @click="submitForm" :disabled="state.submitButtonVisible">确定</el-button>
            <el-button type="warning" @click="loginClick">去登录</el-button>
          </div>
        </el-form>  
      </div>
    </div>
  </template>
  
<script setup>
  import axios from '@/utils/axios'
  import router from '@/router'
  import { reactive, ref } from 'vue'
  import { localSet, pathMap, logoUrl } from '@/utils'
  import { onMounted } from "@vue/runtime-core"  
  import { SuccessFilled, CircleCloseFilled } from '@element-plus/icons-vue'
  import { ElMessage, ElMessageBox } from 'element-plus'

  const signinForm = ref(null) 
  const sendPhoneCoseRef = ref(null)
  // 验证手机号码是否合法
  const checkTelephone =(rule, telephone, callback)=> {
    var reg=/^[1][3,4,5,7,8][0-9]{9}$/g;
    if (!reg.test(telephone)) {
        return false;
    } else {
        return true;
    }
  }
  // 验证短信码是否合法
  const checkPhonCode=(rule, phoneCode, callback)=>{
    var reg=/^\d{6}$/g;
    if (!reg.test(phoneCode)) {
        return false;
    } else {
        return true;
    }
  }
  const state = reactive({ 
    phoneCodeOK: false,
    phoneCodeInput: true,
    phoneNumberOk: false,
    captchaCodeOk: false,
    submitButtonVisible: true,
    getPhoneCodeButtonOK: true,
    clientCode: Number,
    sendPhoneCodeVisible: false,
    captcha_picture: '',   
    ruleForm: {
      phone: '',
      phoneCode: '',
      captchaCode: '',
    },
    checked: true,
    rules: {     
      phone: [
        { required: 'true', message: '手机不能空', trigger: 'blur' },
        {validator: checkTelephone, trigger: 'blur'}
      ],
      phoneCode:[
        { required: 'true', message: '短信码不能空', trigger: 'blur' },
        {validator: checkPhonCode, trigger: 'blur'}
      ],
      captchaCode:[
        { required: 'true', message: '验证码不能空', trigger: 'blur' }
      ],
    }
  })
  // 通过服务器检测手机验证码是否正确
  const sendCheckPhoneCode=()=>{
    let params = {
      phoneNumber: state.ruleForm.phone, 
      phoneCode: state.ruleForm.phoneCode,
      clientCode: state.clientCode,
      captchaCode: state.ruleForm.captchaCode,
    }
    axios.get('/CheckPhoneCode/', {params}).then(res => {
        if(res.code==200){
          state.phoneCodeOK = res.data.results
        }else{
          state.phoneCodeOK = false
          ElMessage.error("短信验证码错误！")
        }
        state.submitButtonVisible = !state.phoneCodeOK
    })
    .catch((error)=>{
      console.log("短信验证码失败！", error)
    })
  }
  // 触发发送短信按钮开启
  const verifySendPhoneCodeButtonUsable=()=>{
    console.log("2个变量：",state.phoneNumberOk,state.captchaCodeOk)
    if(state.phoneNumberOk & state.captchaCodeOk)
    {
      state.getPhoneCodeButtonOK = false    //发送短信按钮可用（开启）
    }else{
        state.getPhoneCodeButtonOK = true
    }

    console.log("按钮可用：", state.getPhoneCodeButtonOK)
  }  

  // 手机验证码验证事件
  const checkPhoneCodeBlur=()=>{
    if(sendCheckPhoneCode() ==false){
      ElMessage.error("验证码输入错误，请点击图片后再输入！")
    }
  }
  // 通过服务器检验手册号码是否可用，如果可用，检测开启发送短信按钮
  const sendCheckPhoneUsable=()=>{
    let params = { phoneNumber: state.ruleForm.phone}
    axios.get(`/UserModelViewSet/phone_number_exit/`, {params}).then(res => {
      console.log("手机号码返回：", res)
        if(res.code==200){
          state.phoneNumberOk = res.data.results
          verifySendPhoneCodeButtonUsable()
        }else{
          state.phoneNumberOk = false
          state.getPhoneCodeButtonOK = true     //发送短信按钮不可用
          ElMessage.error("手机号码不存在！")
        }        
    })
    .catch((error)=>{
      state.phoneNumberOk = false
      console.log("手机号码查询错误", error)
    })
  }
  // 处理手机号码可用事件
  const checkPhoneUsableBlur=()=>{
    sendCheckPhoneUsable()
  }
  // 通过服务器检验校对用户输入的验证码是否正确
  const sendCheckCapchaCode=()=>{
    let params = { clientCode: state.clientCode, captchaCode: state.ruleForm.captchaCode }
    axios.get('/CheckCaptchaCode/', {params}).then(res => {
        if(res.code==200){
          state.captchaCodeOk = true
          verifySendPhoneCodeButtonUsable()
        }else{
          state.captchaCodeOk = false
          state.sendPhoneCodeVisible = false
          state.getPhoneCodeButtonOK = true      //关闭发送短信按钮可用
          ElMessage.error("验证码错误，请刷新图片重新输入！")
        }
    })
    .catch((error)=>{
      console.log("检测验证码失败", error)
    })
  }
  // 处理输入图像验证码事件
  const checkCapchaCodeBlur=()=>{
    sendCheckCapchaCode()
  }
  //获取图像
  const getCaptchaPictureWithClientCode=()=>{
    const min = 10000000
    const max = 99999099
    const a = Math.floor(Math.random() * (max - min + 1)) + min
    state.clientCode = a
    console.log("图像验证码：", state.clientCode)
    let params = { clientCode: state.clientCode }
    axios.get('/CaptchaPictureWithClientCode/', {params}).then(res => {
        if(res.code==200){
          console.log('获取base64图片成功：', res)
            state.captcha_picture='data:image/png;base64,' + res.data.results
        }else{
            ElMessage.error("获取图像失败，请联系管理员！")
        }          
    })
    .catch((error)=>{
      console.log("获取图像失败", error)
      ElMessage.warning("获取图片异常，请联系管理员！")
    })
  }
  onMounted(()=>{
    console.log("我已经来到重置密码页面了")
    getCaptchaPictureWithClientCode()
  })
  //发送手机短信息验证码
  const getPhoneCodeClick=()=>{
    let params = {
      phoneNumber: state.ruleForm.phone,      
      clientCode: state.clientCode,
      captchaCode: state.ruleForm.captchaCode,      
    }
    console.log("发送之前的参数", params)
    axios.get('/SendPhoneCodeView/', {params}).then(res => {
        if(res.code==200){
          state.phoneCodeInput = false      //开启短信息验证码可用
          ElMessage.success("发送成功，请查看手机短信息，有效时间为3分钟！")
        }else{
          state.ruleForm.phone = ""
          state.ruleForm.captchaCode = ""
          state.phoneNumberOk = false
          state.captchaCodeOk = false
          ElMessage("发送失败，重新填写资料")
          console.log("发送手机验证码错误：", res)
        }        
    })
    .catch((error)=>{
      console.log("发送手机验证码失败", error)
    })
  }
  //提交重置密码的表单
  const submitForm = async () => {
    signinForm.value.validate((valid, object) => {
      if (valid) {
        let params = {
          phoneNumber: state.ruleForm.phone,      
          clientCode: state.clientCode,
          captchaCode: state.ruleForm.captchaCode,
          real_name: state.ruleForm.real_name, 
          phoneCode: state.ruleForm.phoneCode,
        }
        axios.patch(`/UserModelViewSet/${state.ruleForm.phone}/reset_password/`, params).then(res => {
          if (res.code==200){
            ElMessage.success("你的密码是123456，请及时修改密码")
          }else{
            ElMessageBox.confirm(
                res.data.results,
                'Warning',
                {
                type: 'warning',
                icon: markRaw(Delete),
                }
            )
          }
        }).catch((error)=>{
          console.log("服务器错误:",error)          
        })
      } else{  //输出表单没有通过的原因
        console.log("前端表单没有通过！",obj)
        for (let key in obj) {
          console.log(obj[key][0].message)
          return false;
        }
      }
    })
  }
  //更新图像验证码
  const updatacaptcha=(val)=>{
    state.ruleForm.captchaCode = ''
    getCaptchaPictureWithClientCode()
  }
  //跳转到登录页面
  const loginClick=()=>{
    router.push('/login')
  }
  </script>
  
  <style scoped>
    .signin_body {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      background-color: #fff;
    }
    .signin_container {
      width: 420px;
      height: 500px;
      background-color: #fff;
      border-radius: 4px;
      box-shadow: 0px 21px 41px 0px rgba(0, 0, 0, 0.2);
    }
    .head {
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 20px 0 10px 0;
    }
    .head img {
      width: 80px;
      height: 80px;
      margin-right: 10px;
    }
    .head .title {
      font-size: 28px;
      color: #1BAEAE;
      font-weight: bold;
    }
    .head .tips {
      font-size: 12px;
      color: #999;
    }
    .signinForm {
      width: 70%;
      margin: 0 auto;
    }

    .captcha_picture{
      width:80px;
      height: 30px;
      cursor:pointer;
    }
    .twoButton{
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .send_phone_code{
        display: flex;
        flex-flow: row nowrap;
        
    }
  </style>